<?php
namespace App\Repositories;
use App\Model\Menu as MenuModel;
use App\Model\Access;
use App\Events\MenuStored;
use App\Events\MenuRemoved;
use Illuminate\Validation\ValidationException;
use collect;

class Menu implements Repository
{
	/***
	保存菜单
	***/
	public function store($data,$notify){
		
		if(isset($data['id'])){
			
			$menu=MenuModel::where("id",$data['id'])->first();
			
			$menu->update($data);
			
			$notify["method"]="edit";

		}else{
			
			$menu=MenuModel::create($data);
			
			$notify["method"]="add";

		}
		
		if(isset($data["access"])){
			
			$access=Access::whereIn("id",$data["access"])->where("parent_id",">",0)->distinct()->get(["parent_id"]);

			$access=array_merge(collect($access->toArray())->flatten()->toArray(),$data["access"]);
			
			$menu->access()->sync($access);
		}

		event(new MenuStored($menu,$notify));
		
		return true ;
	}
	
	/*删除菜单*/
	public function remove($data,$notify)
	{
		if(!$menus=MenuModel::where(function($query) use ($data){
                $query->whereIn('id', $data);
				$query->orWhereIn("parent_id",$data);
        })->where('is_system','<>',1)->get()){
			return true;
		}
		
		MenuModel::where(function($query) use ($data){
                $query->whereIn('id', $data);
				$query->orWhereIn("parent_id",$data);
        })->where('is_system','<>',1)->delete();
		
		foreach($menus as $menu){
			$menu->access()->detach();//删除关联
		}
        $notify["method"]="remove";
		  
        event(new MenuRemoved($menus,$notify));
		
        return $menus;

	}
}
